<?php
declare (strict_types = 1);
namespace app\middleware;
use think\Response;
use think\Config;
/**
 * 中间件：检测客户端ip是否存在于block列表
 */
class BlockIP
{
    private $block_ip_list = [];
    public function __construct(Config $config)
    {
        $this->block_ip_list = $config->get('ip.block', []);
    }
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        //Before
        $client_ip = $this->get_client_ip();
        if(in_array($client_ip,$this->block_ip_list)) {
            // block
            return Response::create()->code(403);
        }else {
            $response = $next($request);
            // After
            return $response;
        }
    }
    protected function get_client_ip(){
        if (!empty($_SERVER['HTTP_CLIENT_IP'])){
            $ip_address = $_SERVER['HTTP_CLIENT_IP'];
        }
        elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
            $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
        else{
            $ip_address = $_SERVER['REMOTE_ADDR'];
        }
        return $ip_address;
    }
}
